package com.hnas.eastsquare.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Component;

import com.hnas.core.dao.BaseDaoImpl;
import com.hnas.core.util.StringUtil;
import com.hnas.eastsquare.domain.EastSquareCountAndAmount;
import com.hnas.eastsquare.orm.SediBalanceChangeRecord;

@Component("sediBalanceChangeRecordDao")
public class SediBalanceChangeRecordDaoImpl extends BaseDaoImpl<SediBalanceChangeRecord> implements SediBalanceChangeRecordDao{

	public SediBalanceChangeRecordDaoImpl() {
		super(SediBalanceChangeRecord.class);
	}

	@Override
	public SediBalanceChangeRecord saveOrUpdate(SediBalanceChangeRecord vo) throws Exception {
		if(vo == null||StringUtil.isEmpty(vo.getId())) return null;
		SediBalanceChangeRecord entity = this.entityManager.find(SediBalanceChangeRecord.class, vo.getId());
		if(entity == null){
			vo.setCreateTime(new Date());
			vo.setUpdateTime(new Date());
			this.entityManager.persist(vo);
		}else{
			vo.setUpdateTime(new Date());
			this.entityManager.merge(vo);
		}
		return vo;
	}

	@Override
	public List<SediBalanceChangeRecord> findEastSquareAll(String date) {
		String hql = "select * from tbl_sedi_balance_change_record t "
				+ "where DATE_FORMAT(t.create_time,'%Y%m%d') >= ?1 and t.is_deleted = ?2";
		Query query = this.entityManager.createNativeQuery(hql,SediBalanceChangeRecord.class);
		query.setParameter(1, date);
		query.setParameter(2, "1");
		return query.getResultList();
	}

	@Override
	public EastSquareCountAndAmount getCountAndAmount(String date) {
		String hql = "select count(t.id),sum(t.balance_change) from tbl_sedi_balance_change_record t "
				+ "where DATE_FORMAT(t.create_time,'%Y%m%d') >= ?1 and t.is_deleted = ?2";
		Query query = this.entityManager.createNativeQuery(hql);
		query.setParameter(1, date);
		query.setParameter(2, "1");
		Object[] result = (Object[]) query.getSingleResult();
		if(result != null){
			EastSquareCountAndAmount vo = new EastSquareCountAndAmount();
			vo.setCount(Integer.valueOf(result[0].toString()));
			vo.setAmount(Long.valueOf(result[1]==null?"0":result[1].toString()));
			return vo;
		}
		return null;
	}

	@Override
	public SediBalanceChangeRecord findByOrderNo(String orderNo) {
		String hql = "select * from tbl_sedi_balance_change_record t "
				+ "where t.order_no = ?1";
		Query query = this.entityManager.createNativeQuery(hql,SediBalanceChangeRecord.class);
		query.setParameter(1, orderNo);
		List<SediBalanceChangeRecord> list = query.getResultList();
		if(list != null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}

}
